package com.qvtu.springboot.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.github.pagehelper.PageInfo;
import com.qvtu.springboot.Common.Result;
import com.qvtu.springboot.entity.Employee;
import com.qvtu.springboot.service.EmployeeService;
import jakarta.annotation.Resource;
import jakarta.annotation.Resources;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@RestController
//加前缀
@RequestMapping("/employee")
public class EmployeeController {
    @Resource
    private EmployeeService employeeService;

    //    新增数据
    @PostMapping("/add")
//    @RequestBody可以将前端传过来的json映射成java对象 或者数组
    public Result add(@RequestBody Employee employee) {
        employeeService.add(employee);
        return Result.success();

    }

    //删除数据
    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable Integer id) {
        employeeService.deleteById(id);
        return Result.success("删除成功");
    }

//    批量删除数据
    @DeleteMapping("/deleteBatch")
    public Result deleteBatch(@RequestBody List<Integer> ids){
        employeeService.deleteBatch(ids);
        return Result.success("批量删除成功");
    }

    //    修改数据
    @PutMapping("/update")
    public Result update(@RequestBody Employee employee) {
        employeeService.update(employee);
        return Result.success("修改成功");
    }


    //    查询单个参数
    @GetMapping("/selectById/{id}")
//    @PathVariable注解可以传递路径参数(路径对应形式localhost:8080/employee/selectById/1)
    public Result selectById(@PathVariable Integer id) {
        Employee employee = employeeService.selectById(id);
        return Result.success(employee);
    }

    //    查询所有的数据
    @GetMapping("/selectAll")
    public Result selectAll(Employee employee) {
        List<Employee> list = employeeService.selectAll(employee);
        return Result.success(list);
    }


    //    分页查询
//    pageNum 当前页码
//    pageSize 每页的个数
    @GetMapping("/selectPage")
    public Result selectPage(Employee employee,
                             @RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize) {
        PageInfo<Employee> pageInfo = employeeService.selectPage(employee,pageNum, pageSize);
        return Result.success(pageInfo);
    }

//    导出excel数据
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
//        拿到使用的员工数据
        List<Employee> employeeList=employeeService.selectAll(null);
//        构建excelWriter
//        在内存操作 写出到浏览器(写入到内存中) 这里的true表示是一个xlsx文件（也就是excel文件）
        ExcelWriter writer = ExcelUtil.getWriter(true);
//        设置别名（中文表头）
        writer.addHeaderAlias("username","账号");
        writer.addHeaderAlias("name","名称");
        writer.addHeaderAlias("sex","性别");
        writer.addHeaderAlias("no","工号");
        writer.addHeaderAlias("age","年龄");
        writer.addHeaderAlias("description","个人介绍");
        writer.addHeaderAlias("departmentName","部门");
//        默认的 为添加别名的也会被写出 如果只需要导出设置了别名的字段库调用该方法排除
        writer.setOnlyAlias(true);
//        写出数据到输出流writer
        writer.write(employeeList,true);
//        设置输出文件的名称 以及输出流的头信息
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName= URLEncoder.encode("员工信息","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
//        写出到输出流 并关闭writer
        ServletOutputStream os = response.getOutputStream();
        writer.flush(os);
        writer.close();
    }

    @PostMapping("/import")
// MultipartFile 是 Spring 提供的一个接口，用于处理文件上传。它封装了上传的文件信息，包括文件名、文件内容、文件大小等
    public Result imp(MultipartFile file) throws Exception{
// 从上传的MultipartFile对象中获取输入流 用于读取内容
        InputStream inputStream=file.getInputStream();
//        使用excel工具类创建一个excelReader对象，用于读取excel文件输入流（内容）
        ExcelReader reader=ExcelUtil.getReader(inputStream);
        reader.addHeaderAlias("账号","username");
        reader.addHeaderAlias("名称","name");
        reader.addHeaderAlias("性别","sex");
        reader.addHeaderAlias("工号","no");
        reader.addHeaderAlias("年龄","age");
        reader.addHeaderAlias("个人介绍","description");
        reader.addHeaderAlias("部门","departmentName");
//        读取excel里面的数据
//        使用excelReader对象读取excel文件中的全部数据 并将没一行的数据映射为employee类的实例
        List<Employee> employeeList=reader.readAll(Employee.class);
//        写入list输入到数据库
        for(Employee employee:employeeList){
            employeeService.add(employee);
        }
        return Result.success();
    }


}
